package com.telit.firecommand.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.telit.common.exception.ForestBaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geojson.feature.FeatureJSON;
import org.opengis.feature.simple.SimpleFeature;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


@Slf4j
public class UnZipUtils {

    /**
     * 保存zip文件到本地并调用解压方法并返回解压出的文件的路径集合
     * @return list //解压出的文件的路径合集
     */
    public static List<String> batchadd(File newFile) {
        List<String> list = new ArrayList<>();
        try {
            list = unZipFiles(newFile, newFile.getPath());//解压文件，获取文件路径
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解压执行失败");
        }
        //程序结束时，删除临时文件
        deleteFiles(newFile.getPath());
        return list;
    }

    /**
     * zip解压
     *
     * @param srcFile     zip源文件
     * @param destDirPath 解压后的目标文件夹
     * @return list 解压文件的路径合集
     * @throws RuntimeException 解压失败会抛出运行时异常
     */
    public static List<String> unZipFiles(File srcFile, String destDirPath) throws RuntimeException {
        List<String> list = new ArrayList<>();
        long start = System.currentTimeMillis();
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile);
            Enumeration<?> entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                log.info("解压" + entry.getName());
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    list.add(destDirPath + entry.getName());
                    if (!targetFile.getParentFile().exists()) {
                        log.info("父文件不存在");
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
            log.info("解压完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new ForestBaseException("文件解析失败,e:" + e);
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    /**
     * @param filePath 临时文件的删除
     *                 删除文件夹里面子目录
     *                 再删除文件夹
     */
    public static void deleteFiles(String filePath) {
        File file = new File(filePath);
        if ((!file.exists()) || (!file.isDirectory())) {
            log.info("file not exist");
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (filePath.endsWith(File.separator)) {
                temp = new File(filePath + tempList[i]);
            } else {
                temp = new File(filePath + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                deleteFiles(filePath + "\\" + tempList[i]);
            }
        }
        // 空文件的删除
        file.delete();
    }

    /**
     * 从shape文件中获取经纬度
     * @param shpFile
     * @return
     * @throws IOException
     */
    public static List<String> getCoordinateFromShape(String shpFile) throws IOException {
        List<String> resultList = new ArrayList<>();
        // 使用GeoTools读取ShapeFile文件
        File shapeFile = new File(shpFile);
        ShapefileDataStore store = new ShapefileDataStore(shapeFile.toURI().toURL());
        //设置编码
        Charset charset = Charset.forName("GBK");
        store.setCharset(charset);
        SimpleFeatureSource sfSource = store.getFeatureSource();
        SimpleFeatureIterator sfIter = sfSource.getFeatures().features();
        // 从ShapeFile文件中遍历每一个Feature，然后将Feature转为GeoJSON字符串
        StringWriter writer = null;
        while (sfIter.hasNext()) {
            SimpleFeature feature = sfIter.next();
            // Feature转GeoJSON
            FeatureJSON fjson = new FeatureJSON();
            writer = new StringWriter();
            fjson.writeFeature(feature, writer);
            String sjson = writer.toString();
            JSONObject object = JSON.parseObject(sjson,JSONObject.class);
            String geometry = object.getString("geometry");
            JSONObject geometryObject = JSON.parseObject(geometry,JSONObject.class);
            String coordinates = geometryObject.getString("coordinates");
            resultList.add(coordinates);
        }
        // 关闭资源
        sfIter.close();
        store.dispose();
        if(shapeFile.exists() && writer!= null){
            writer.close();
        }
        return resultList;
    }


}

